package com.fl.nj.service.impl;

import com.fl.nj.entity.DbInfo;
import com.fl.nj.entity.DatabaseConfig;
import com.fl.nj.mapper.DbInfoMapper;
import com.fl.nj.service.DbInfoService;
import com.fl.nj.service.DatabaseConfigService;
import com.fl.nj.util.SchemaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.*;

/**
 * 数据库信息Service实现类
 * 实现数据库信息的业务操作
 */
@Service
public class DbInfoServiceImpl implements DbInfoService {
    
    @Autowired
    private DbInfoMapper dbInfoMapper;
    
    @Autowired
    private DatabaseConfigService databaseConfigService;

    @Override
    public boolean save(DbInfo dbInfo) {
        return dbInfoMapper.save(dbInfo) > 0;
    }

    @Override
    @Transactional
    public int batchSave(List<DbInfo> dbInfoList) {
        return dbInfoMapper.batchSave(dbInfoList);
    }

    @Override
    public boolean update(DbInfo dbInfo) {
        return dbInfoMapper.update(dbInfo) > 0;
    }

    @Override
    public DbInfo getById(Long id) {
        return dbInfoMapper.getById(id);
    }

    @Override
    public List<DbInfo> getByDbConfigId(Long dbConfigId) {
        return dbInfoMapper.getByDbConfigId(dbConfigId);
    }

    @Override
    public DbInfo getByDbConfigIdAndDbName(Long dbConfigId, String dbName) {
        Map<String, Object> params = new HashMap<>();
        params.put("dbConfigId", dbConfigId);
        params.put("dbName", dbName);
        return dbInfoMapper.getByDbConfigIdAndDbName(params);
    }

    @Override
    public List<DbInfo> getPageList(Map<String, Object> params) {
        // 处理分页参数
        Integer page = (Integer) params.get("page");
        Integer pageSize = (Integer) params.get("pageSize");
        if (page != null && pageSize != null) {
            params.put("offset", (page - 1) * pageSize);
        }
        return dbInfoMapper.getPageList(params);
    }

    @Override
    public int getTotal(Map<String, Object> params) {
        return dbInfoMapper.getTotal(params);
    }

    @Override
    public boolean delete(Long id) {
        return dbInfoMapper.delete(id) > 0;
    }

    @Override
    @Transactional
    public int deleteByDbConfigId(Long dbConfigId) {
        return dbInfoMapper.deleteByDbConfigId(dbConfigId);
    }

    @Override
    @Transactional
    public Map<String, Object> syncDatabasesFromConfig(Long dbConfigId) {
        Map<String, Object> result = new HashMap<>();
        int successCount = 0;
        int updateCount = 0;
        List<String> errorDatabases = new ArrayList<>();
        
        try {
            // 获取数据库配置
            DatabaseConfig dbConfig = databaseConfigService.getById(dbConfigId);
            if (dbConfig == null) {
                result.put("success", false);
                result.put("message", "数据库配置不存在");
                return result;
            }
            
            // 从数据库配置获取所有数据库信息
            List<Map<String, Object>> databases = SchemaUtil.getAllDatabases(dbConfig);
            
            if (databases == null || databases.isEmpty()) {
                result.put("success", true);
                result.put("message", "没有找到数据库信息");
                result.put("successCount", 0);
                result.put("updateCount", 0);
                result.put("errorCount", 0);
                return result;
            }
            
            // 处理每个数据库信息
            for (Map<String, Object> dbMap : databases) {
                try {
                    String dbName = (String) dbMap.get("dbName");
                    String dbType = (String) dbMap.get("dbType");
                    
                    // 检查数据库信息是否已存在
                    DbInfo existingDbInfo = getByDbConfigIdAndDbName(dbConfigId, dbName);
                    
                    if (existingDbInfo != null) {
                        // 更新现有数据库信息
                        existingDbInfo.setDbType(dbType);
                        existingDbInfo.setUpdateTime(new Date());
                        
                        // 尝试获取表数量（如果可用）
                        if (dbMap.containsKey("tablesCount")) {
                            existingDbInfo.setTablesCount((Integer) dbMap.get("tablesCount"));
                        }
                        
                        if (update(existingDbInfo)) {
                            updateCount++;
                        } else {
                            errorDatabases.add(dbName);
                        }
                    } else {
                        // 创建新的数据库信息
                        DbInfo newDbInfo = new DbInfo();
                        newDbInfo.setDbConfigId(dbConfigId);
                        newDbInfo.setDbName(dbName);
                        newDbInfo.setDbType(dbType);
                        newDbInfo.setStatus("NORMAL");
                        
                        // 尝试获取表数量（如果可用）
                        if (dbMap.containsKey("tablesCount")) {
                            newDbInfo.setTablesCount((Integer) dbMap.get("tablesCount"));
                        }
                        
                        if (save(newDbInfo)) {
                            successCount++;
                        } else {
                            errorDatabases.add(dbName);
                        }
                    }
                } catch (Exception e) {
                    // 记录单个数据库处理失败的情况
                    errorDatabases.add((String) dbMap.get("dbName"));
                }
            }
            
            // 设置同步结果
            result.put("success", true);
            result.put("message", String.format("数据库同步完成：新增 %d 个，更新 %d 个，失败 %d 个", 
                    successCount, updateCount, errorDatabases.size()));
            result.put("successCount", successCount);
            result.put("updateCount", updateCount);
            result.put("errorCount", errorDatabases.size());
            result.put("errorDatabases", errorDatabases);
            
        } catch (SQLException e) {
            result.put("success", false);
            result.put("message", "同步数据库信息失败: " + e.getMessage());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "操作失败: " + e.getMessage());
        }
        
        return result;
    }
}